//
//  AppDelegate.m
//  shortvideoplay
//
//  Created by adam on 2024/6/12.
//

#import "AppDelegate.h"
#import "QZHomePlayVC.h"
#import "QZTabbarController.h"
#import "DJNavigationController.h"
#import "IQKeyboardManager.h"
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import "CSJADLoading.h"
#import "QZHongBaoView.h"
#import "QZKaiPingVC.h"
#import <UserNotifications/UserNotifications.h>
#import <UMCommon/UMCommon.h>

@interface AppDelegate ()<SDWebImageCacheKeyFilter>
@property (assign, nonatomic)double startTime;
@property (assign, nonatomic)NSInteger activeTime;
@property (strong, nonatomic) NSTimer * activeTimer;
@property (strong, nonatomic) NSTimer * requestTimer;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    if (self.window == nil) {
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.window makeKeyAndVisible];
    }
    [UMConfigure initWithAppkey:@"66ff86ab80464b33f6d43ac7" channel:@"App Store"];
    
    if([QZUserInfoModel isLogin]){
        NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:QZUserInfoKey];
        [[QZUserInfoModel share] setValuesForKeysWithDictionary:user];
    }
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;

    QZKaiPingVC * kaiping = [[QZKaiPingVC alloc]init];
    kaiping.isQiDong = YES;
    kaiping.modalPresentationStyle = UIModalPresentationFullScreen;
    self.window.rootViewController = kaiping;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestTimeTap) name:@"requestTime" object:nil];
    //缓存图片防盗链
    [[SDWebImageManager sharedManager] setCacheKeyFilter:self];
    return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *pushToken = [Tools getHexStringForData:deviceToken];
    [QZUserInfoModel share].pushToken = pushToken;
    //这里不考虑ios 10以下的系统了 最低支持到11 或 12
//    TFWeakSelf(self)
    [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        KMutableDic(sendDic)
        sendDic[@"device_token"] = deviceToken;
        if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
            [QZUserInfoModel share].lastPushStatus = NO;
            sendDic[@"is_open"] = @(NO);
        }else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
            sendDic[@"is_open"] = @(NO);
            [QZUserInfoModel share].lastPushStatus = NO;
        }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
            [QZUserInfoModel share].lastPushStatus = YES;
            sendDic[@"is_open"] = @(YES);
        }
        [YBNetBase saveDeviceTokenRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
            
        }];
    }];
}
- (nullable NSString *)cacheKeyForURL:(nonnull NSURL *)url {
    if (url == nil) return nil;
    NSURLComponents *components = [[NSURLComponents alloc] init];
    components.scheme = url.scheme;
    components.host = url.host;
    components.path = url.path;
    NSURL *_url = components.URL;
    return [_url absoluteString];
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
    if(self.startTime == 0){
        self.startTime = CACurrentMediaTime();
    }else{
        CFTimeInterval newTime = CACurrentMediaTime();
        if(newTime - self.startTime > 600){
            self.startTime = newTime;
            QZKaiPingVC * kaiping = [[QZKaiPingVC alloc]init];
            kaiping.modalPresentationStyle = UIModalPresentationFullScreen;
            [[Tools currentActiveController] presentViewController:kaiping animated:NO completion:nil];
        }
    }
}
- (void)applicationDidBecomeActive:(UIApplication *)application{
    [DJXManager startOpenGLESActivity];
    [self idfa];
    if(self.startTime == 0){
        self.startTime = CACurrentMediaTime();
    }
    [self activeStart];
}
- (void)activeStart{
    self.activeTime = 0;
    self.activeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(activeTap) userInfo:nil repeats:YES];
}
- (void)activeTap{
    if(self.activeTime >= 300){
        [self.activeTimer invalidate];
        KMutableDic(sendDic)
        sendDic[@"active_time"] = [NSString stringWithFormat:@"%d",(int)self.startTime];
        if([QZUserInfoModel isLogin]){
            KWeakSelf
            [YBNetBase activeRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                [weakSelf activeStart];
            }];
        }

    }else{
        self.activeTime++;
    }
    
}
- (void)requestTimeTap{
    
    [self.requestTimer invalidate];
    self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(requestTimeEnd) userInfo:nil repeats:NO];
    
    if(self.activeTimer == nil){
        [self activeStart];
    }
}
-(void)requestTimeEnd{
    [self.activeTimer invalidate];
    self.activeTimer = nil;
    self.activeTime = 0;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    [DJXManager stopOpenGLESActivity];
    [self activeTap];
}
- (NSString*)idfa {
    __block NSString *idfa = @"";
    ASIdentifierManager *manager = [ASIdentifierManager sharedManager];
    if (@available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                idfa = [[manager advertisingIdentifier] UUIDString];
            }
        }];
    }else{
        if ([manager isAdvertisingTrackingEnabled]) {
            idfa = [[manager advertisingIdentifier] UUIDString];
        }
    }
    return idfa;
}

@end
